package com.fingard.dsp.bank.directbank.chinaums01;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IH5Order;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqUnifiedOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsUnifiedOrder;
import com.fingard.text.StringHelper;
import com.fingard.text.XmlHelper;

import java.util.Date;
import java.util.HashMap;

/**
 * 银联商务H5支付
 * 
 * 参考文档:
 * 		1、银联商务公众号 服务窗支付接入接口规范 .pdf
 * 		2、认证流程.pdf
 * 
 * @author Cruise
 * @date 2019/4/19
 */
public class ChinaUMS01H5Order extends ChinaUMS01Base implements IH5Order {
	/**
	 * 开发接口:1.1. 下单
	 */
	@Override
	public RetAtsUnifiedOrder submitH5Order(ReqUnifiedOrder p_req) {
		RetAtsUnifiedOrder retAts = new RetAtsUnifiedOrder();
        retAts.rdSeq = p_req.rdSeq;

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req.ownAct, "unifiedorder");
            if (actItem != null) {
            	JSONObject submitH5 = new JSONObject();
            	submitH5.put("requestTimestamp", Format.DateTime14Format.format(new Date()));
            	
            	String srcReserve = "";
            	if ("1".equals(p_req.realNameFlag) && "0".equals(p_req.realNameType)) {
            		JSONObject srcReserveJson = new JSONObject();
            		srcReserveJson.put("payNo", p_req.rdSeq);
            		srcReserveJson.put("authFlag", "TRUE");
            		srcReserveJson.put("authMode", "CIITC");
            		srcReserveJson.put("authTransId", p_req.paymentNo);
            		srcReserveJson.put("merInstId", actItem.inMerchantId);
            		srcReserveJson.put("version", "1.0");
            		srcReserve = JSON.toJSONString(srcReserveJson);
            		submitH5.put("srcReserve", srcReserve);
            	}
            	
            	submitH5.put("merOrderId", p_req.rdSeq);
            	submitH5.put("mid", actItem.merchantId);
            	submitH5.put("tid", actItem.termId);
            	submitH5.put("instMid", "YUEDANDEFAULT");
            	
            	JSONObject goodsObj = new JSONObject();
            	goodsObj.put("goodsName", XmlHelper.encode(p_req.description));
            	goodsObj.put("body", XmlHelper.encode(p_req.attach));
            	JSONArray goodsArray = new JSONArray();
            	goodsArray.add(goodsObj);
            	submitH5.put("goods", JSON.toJSON(goodsArray));
            	
            	submitH5.put("attachedData", XmlHelper.encode(p_req.attach));
            	submitH5.put("orderDesc", XmlHelper.encode(p_req.description));
            	submitH5.put("totalAmount", StringHelper.amountMultiply100(p_req.amount));
            	submitH5.put("notifyUrl", actItem.notifyURL);
            	submitH5.put("returnUrl", actItem.returnURL);
            	
            	boolean limitPay = getBankConfig().getValueAsBool("limitPay");
            	submitH5.put("limitCreditCard ", limitPay+"");

            	String bankFrontUrl = bankFront.getUrl("submitH5Order");
                if ("1".equals(p_req.realNameFlag) && "2".equals(p_req.realNameType)) {
                    submitH5.put("fixBuyer", "T");
                    submitH5.put("fixInsurance", "SZ");
                    submitH5.put("paymentInstitution", p_req.paymentInstitution);
                    submitH5.put("companyIdInsurance", p_req.corpNo);
                    submitH5.put("insuranceNumber", p_req.insuPolicyNum);
                    bankFrontUrl = bankFront.getUrl("submitSZH5Order");
                }
            	
            	String result = submitSend(bankFrontUrl, JSON.toJSONString(submitH5), actItem);
            	if (result.length() > 0) {
            		HashMap<String, String> tmpRetMap = new HashMap<String, String>();
                    tmpRetMap.put("Result", result);

                    retAts.respCode = "0";
                    retAts.respInfo = "签名成功";
                    retAts.customHashMap = tmpRetMap;
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "签名失败";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        return retAts;
	}
	
	/**
	 * 开发接口：
	 * 		1、1.2. 支付结果查询
	 * 		2、2. OPEN-BODY-SIG方式
	 */
	@Override
	public RetAtsQueryOrder queryH5Pay(ReqQueryOrder p_req){
		RetAtsQueryOrder retAts = new RetAtsQueryOrder();
        retAts.rdSeq = p_req.rdSeq;

        try {
            ActSetItem actItem = this.getBankConfig().getActSetItem(p_req.ownAct, "unifiedorder");
            if (actItem != null) {
            	JSONObject queryH5 = new JSONObject();
            	queryH5.put("requestTimestamp", Format.DateTimeFormat.format(new Date()));
            	queryH5.put("mid", actItem.merchantId);
            	queryH5.put("merOrderId", p_req.rdSeq);
            	queryH5.put("tid", getBankConfig().getValueAsString("terminalNum"));
            	queryH5.put("instMid", "YUEDANDEFAULT");
            	
            	String tmpStrRet = querySend(bankFront.getUrl("queryH5Pay"), JSON.toJSONString(queryH5), actItem);
            	if (StringHelper.hasAnyChar(tmpStrRet)) {
                    if (tmpStrRet.contains("{")) {
                    	JSONObject tmpJsonResp = JSON.parseObject(tmpStrRet);
                    	retAts.respCode = "0";
                    	retAts.respInfo = tmpJsonResp.getString("errMsg");
                    	String status = tmpJsonResp.getString("status");
                    	if(status!= null){
                            retAts.transState = status;
                            retAts.payInfoCode = tmpJsonResp.getString("errCode");
                            retAts.outTransID = tmpJsonResp.getString("targetOrderId");
                            retAts.oppAct = tmpJsonResp.getString("bankCardNo");
                            retAts.oppBank = tmpJsonResp.getString("bankInfo");
                        }else{
                            retAts.transState = tmpJsonResp.getString("errCode");
                            retAts.payInfoCode = tmpJsonResp.getString("errCode");
                        }
                    } else {
                    	retAts.respCode = "-1";
                    	retAts.respInfo = "银联响应数据格式非法";
                    }
                } else {
                	retAts.respCode = "-1";
                	retAts.respInfo = "银联响应为空";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respCode = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        return retAts;
	}
}
